// /utils/buildViewConfig.ts
export type Item = { species?: string; uuid: string };

export interface BuildOptions {
    baseHiglassURL?: string;
    viewHeight?: number;
    cols?: number; // if omitted, caller can compute (default: ceil(sqrt(n)))
}

/** helper: build layout grid for given views and cols
 *  viewHeight 用来把像素高度映射到网格单位，避免极端高度膨胀
 */
export function makeLayoutForViews(
    views: Array<{ uid: string }>,
    cols: number,
    viewHeight = 400
) {
    const layout: any[] = [];
    // 每个网格单位近似映射为 ~100px（可根据需要调整）
    const unitH = Math.max(6, Math.ceil(viewHeight / 100));

    if (views.length === 1) {
        layout.push({
            i: views[0].uid,
            x: 0,
            y: 0,
            w: 12, // 占满整行
            h: unitH,
            moved: false,
            static: false,
        });
        return layout;
    }


    for (let i = 0; i < views.length; i++) {
        const col = i % cols;
        const row = Math.floor(i / cols);
        layout.push({
            i: views[i].uid,
            x: col * 6,
            y: row * unitH,
            w: 6,
            h: unitH,
            moved: false,
            static: false,
        });
    }
    return layout;
}

/** Build a HiGlass-compatible viewConfig from an array of items (uuid + optional species label)
 *
 * 返回 { viewConfig, viewUids }
 */
export function buildViewConfigFromUuids(
    items: Item[],
    opts: BuildOptions = {}
) {
    const base =
        opts.baseHiglassURL ?? process.env.NEXT_PUBLIC_HIGLASS_URL ?? "";
    const viewHeight = opts.viewHeight ?? 400;
    const cols =
        opts.cols ??
        Math.max(1, Math.ceil(Math.sqrt(Math.max(1, items.length))));

    // create views — 每个 view 带 uid + layout + tracks（至少包含 center heatmap）
    const views = items.map((it, i) => {
        const uid = `view-${i}-${items[i].uuid}`;

        const unitH = Math.max(6, Math.ceil(viewHeight / 100));
        const col = i % cols;
        const row = Math.floor(i / cols);

        return {
            uid,
            layout: {
                w: items.length === 1 ? 12 : 6, // 如果只有一个，直接占满
                h: unitH,
                x: items.length === 1 ? 0 : col * 6,
                y: row * unitH,
                moved: false,
                static: false,
            },
            // 这里的 tracks 结构采用常见的 top/left/center 组织方式
            tracks: {
                top: [],
                left: [],
                center: [
                    {
                        uid: `center-${uid}`,
                        type: "combined",
                        height: viewHeight,
                        options: {},
                        contents: [
                            {
                                uid: `track-${uid}`,
                                filetype: "cooler",
                                server: base,
                                tilesetUid: it.uuid || "",
                                type: "heatmap",
                                options: {
                                    name: it.species ?? "",
                                    // 示例中常用的一些选项（根据需要可扩展）
                                    labelShowAssembly: true,
                                    labelShowResolution: true,
                                    minWidth: 100,
                                    minHeight: 100,
                                },
                                // transforms: [] // 如果需要可以在此添加 transforms
                            },
                        ],
                    },
                ],
                right: [],
                bottom: [],
                whole: [],
                gallery: [],
            },
            // 你可以按需添加 initialXDomain / initialYDomain
        };
    });

    // layout 顶层数组（与视图内 layout 对齐）
    const layout = makeLayoutForViews(views, cols, viewHeight);

    // 生成 lock id，使所有 view 使用同一个 lock -> HiGlass 层面实现联动
    const lockUid = `L${Date.now().toString(36)}${Math.random()
        .toString(36)
        .slice(2, 6)}`;
    const zoomLockUid = `Z${Date.now().toString(36)}${Math.random()
        .toString(36)
        .slice(2, 6)}`;


    const locationLocksByViewUid: Record<string, string> = {};
    const zoomLocksByViewUid: Record<string, string> = {};
    for (const v of views) {
        locationLocksByViewUid[v.uid] = lockUid;
        zoomLocksByViewUid[v.uid] = zoomLockUid;
    }

    // locksDict 在这里放最小信息（uid）。HiGlass 会在运行时填充具体数值。
    const locationLocks = {
        locksByViewUid: locationLocksByViewUid,
        locksDict: {
            [lockUid]: {
                uid: lockUid,
                // 可选：初始化值（如果你知道初始 domain，可在这里填入每个 view 的 domain）
                // e.g. [viewUid]: [xStart, xEnd, span]
            },
        },
    };

    const zoomLocks = {
        locksByViewUid: zoomLocksByViewUid,
        locksDict: {
            [zoomLockUid]: {
                uid: zoomLockUid,
            },
        },
    };

    const viewConfig = {
        editable: true,
        zoomFixed: false,
        exportViewUrl: base ? `${base}/viewconfs/` : undefined,
        trackSourceServers: base ? [base] : [],
        views,
        layout,
        // 下面两项实现 view 层面的联动（location + zoom）
        locationLocks,
        zoomLocks,
        // valueScaleLocks 保留空结构（可按需实现）
        valueScaleLocks: {
            locksByViewUid: {},
            locksDict: {},
        },
    };

    return { viewConfig, viewUids: views.map((v) => v.uid) };
}
